package yc.gg.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;
import yc.gg.constants.Constants;
import yc.gg.domain.dto.CreatePayRequestDTO;
import yc.gg.domain.dto.OrderAnimalDTO;
import yc.gg.domain.po.PayOrder;
import yc.gg.domain.req.ShopCartReq;
import yc.gg.domain.res.PayOrderRes;
import yc.gg.domain.vo.ProductVO;
import yc.gg.mapper.OrderMapper;
import yc.gg.service.IOrderService;
import org.apache.commons.lang3.RandomStringUtils;
import yc.gg.utils.Result;
import yc.gg.utils.UserHolder;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * \* User: Fuyue
 * \* Date: 2025/6/6
 * \* Description:
 * \
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Resource
    private OrderMapper orderMapper;


    @Override
    public PayOrderRes createOrder(ShopCartReq shopCartReq) {
        String userId = UserHolder.getUser().getOpenid();
        // 查询当前用户是否存在未支付订单或掉单订单
        PayOrder payOrderReq = new PayOrder();
        payOrderReq.setUserId(shopCartReq.getUserId());
        payOrderReq.setAnimalsId(shopCartReq.getAnimalsId());

        PayOrder unpaidOrder = orderMapper.queryUnPayOrder(payOrderReq);
        if (null != unpaidOrder && Constants.OrderStatusEnum.PAY_WAIT.getCode().equals(unpaidOrder.getStatus())) {
            log.info("创建订单-存在，已存在未支付订单。userId:{} productId:{} orderId:{}",
                    shopCartReq.getUserId(), shopCartReq.getAnimalsId(), unpaidOrder.getOrderId());
            // 直接返回订单ID，不包含支付链接
            return PayOrderRes.builder()
                    .orderId(unpaidOrder.getOrderId())
                    .createTime(unpaidOrder.getCreateTime())
                    .status(Constants.OrderStatusEnum.PAY_WAIT.getCode())
                    .build();
        } else if (null != unpaidOrder && Constants.OrderStatusEnum.CREATE.getCode().equals(unpaidOrder.getStatus())) {
            log.info("创建订单-存在，存在未创建支付的订单。userId:{} productId:{} orderId:{}", shopCartReq.getUserId(), shopCartReq.getAnimalsId(), unpaidOrder.getOrderId());

            unpaidOrder.setStatus(Constants.OrderStatusEnum.PAY_WAIT.getCode());
            unpaidOrder.setOrderTime(new Date());
            orderMapper.updateOrderStatus(unpaidOrder);

            return PayOrderRes.builder()
                    .createTime(unpaidOrder.getCreateTime())
                    .status(Constants.OrderStatusEnum.CREATE.getCode())
                    .build();
        }

        // 查询宠物信息
        ProductVO productVO = orderMapper.queryAnimalByAnimalId(shopCartReq.getAnimalsId());
        // 生成订单ID
        String orderId = RandomStringUtils.randomNumeric(16);

        //修改动物状态
        orderMapper.updateAnimalState(1,shopCartReq.getAnimalsId(),userId);

        // 创建订单（状态为已确认，无需支付）
        PayOrder newOrder = PayOrder.builder()
                .userId(shopCartReq.getUserId())
                .animalsId(shopCartReq.getAnimalsId())
                .productName(productVO.getProductName())
                .orderId(orderId)
                .totalAmount(productVO.getPrice())
                .createTime(new Date())
                .status(Constants.OrderStatusEnum.PAY_WAIT.getCode()) // 标记为待付款
                .build();

        orderMapper.insert(newOrder);

        return PayOrderRes.builder()
                .orderId(orderId)
                .createTime(new Date())
                .build();
    }

    @Override
    public void changeOrderPaySuccess(String orderId) {
        PayOrder payOrderReq = new PayOrder();
        payOrderReq.setOrderId(orderId);
        payOrderReq.setStatus(Constants.OrderStatusEnum.PAY_SUCCESS.getCode());
        orderMapper.changeOrderPaySuccess(payOrderReq);
    }

    @Override
    public List<String> queryNoPayNotifyOrder() {
        return orderMapper.queryNoPayNotifyOrder();
    }

    @Override
    public List<String> queryTimeoutCloseOrderList() {
        return orderMapper.queryTimeoutCloseOrderList();
    }

    @Override
    public boolean changeOrderClose(String orderId) {
        return orderMapper.changeOrderClose(orderId);
    }

    @Override
    public Result ensure(String orderId) {
        try {
            PayOrder payOrder = orderMapper.queryOrderByIdAndUserId(orderId);

            //  检查订单状态是否可以被确认（通常应该是已支付状态）
            if (!Constants.OrderStatusEnum.PAY_WAIT.getCode().equals(payOrder.getStatus())) {
                log.error("订单状态不正确，无法确认，orderId: {}, 当前状态: {}",
                        orderId, payOrder.getStatus());
                return Result.error("订单状态不正确，无法确认");
            }

            payOrder.setStatus(Constants.OrderStatusEnum.PAY_SUCCESS.getCode());
            payOrder.setUpdateTime(new Date());

            int rows = orderMapper.updateOrderStatus(payOrder);
            if (rows > 0) {
                log.info("订单支付成功，orderId: {}", orderId);
//                orderMapper.updateAnimalState(1,payOrder.getAnimalsId(),userId);
                return Result.success("订单支付成功");
            } else {
                log.error("订单支付失败，orderId: {}", orderId);
                return Result.error("订单支付失败");
            }
        } catch (Exception e) {
            log.error("订单支付过程发生异常，orderId: {}", orderId, e);
            return Result.error("订单支付过程发生异常，请稍后重试");
        }
    }

    @Override
    public Result mine() {
        String openid = UserHolder.getUser().getOpenid();
        List<OrderAnimalDTO> list = orderMapper.mine(openid);
        return Result.success(list);
    }
}